#!/bin/bash

# 规则内容
RULES=$(cat <<EOF
# 鼠标规则
SUBSYSTEM=="input", ATTRS{product}=="USB Mouse", SYMLINK+="usb_mouse"

# 键盘规则
SUBSYSTEM=="input", ATTRS{product}=="USB Keyboard", SYMLINK+="usb_keyboard"
EOF
)

# 规则文件路径
RULES_FILE="/etc/udev/rules.d/99-usb-input.rules"

# 检查规则文件目录是否存在
if [ ! -d "$(dirname "$RULES_FILE")" ]; then
    echo "规则文件目录不存在，创建目录..."
    mkdir -p "$(dirname "$RULES_FILE")"
fi

# 检查规则是否已经存在
if [ -f "$RULES_FILE" ]; then
    existing_rules=$(cat "$RULES_FILE")
    for rule in $(echo "$RULES" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'); do
        if [[ -n "$rule" && ! "$existing_rules" =~ "$rule" ]]; then
            new_rules=true
        elif [[ -n "$rule" && "$existing_rules" =~ "$rule" ]]; then
            echo "规则 '$rule' 已存在，跳过写入。"
        fi
    done
else
    new_rules=true
fi

# 如果有新规则，将规则内容写入文件
if [ "$new_rules" = true ]; then
    echo "$RULES" | tee -a "$RULES_FILE" > /dev/null
    if [ $? -eq 0 ]; then
        echo "规则已成功写入 $RULES_FILE"
        # 重新加载 udev 规则
        udevadm control --reload-rules
        udevadm trigger
        echo "udev 规则已重新加载并触发"
    else
        echo "写入规则文件时出错"
    fi
else
    echo "所有规则已存在，无需写入。"
fi
